﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PSS4Publish.Repositories.Domain;
using PSS4Publish.Common;
using System.Xml;
using System.Xml.Linq;

namespace PSS4Publish.AppConsole
{
    class CruiseControlWrapper
    {
        public ResultStatus GetStatusPublish(string projectName, string ccnetReport)
        {
            ResultStatus rs = new ResultStatus();
            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.Load(ccnetReport);

            XDocument doc = XDocument.Parse(xmlDoc.InnerXml);

            List<string> listXml = new List<string>();

            foreach (var item in doc.Root.Elements("Project").ToList())
            {
                listXml.Add(item.ToString());
            }

            XmlNodeList nodeList = xmlDoc.SelectNodes("Projects/Project");

            foreach (XmlNode item in nodeList)
            {
                string nameProject = item.Attributes["name"].Value;

                if (nameProject == projectName)
                {
                    string lastBuildStatus = item.Attributes["lastBuildStatus"].Value;
                    string activity = item.Attributes["activity"].Value;

                    if (EnumConverter<BuildStatus>.ConvertToEnum(lastBuildStatus) == BuildStatus.Success
                        && EnumConverter<BuildActivity>.ConvertToEnum(activity) == BuildActivity.Sleeping)
                    {
                        rs.SetSuccessStatus("Publish Can Execute");
                    }
                    else
                    {
                        rs.SetErrorStatus("Can't be Execute Because Publish Not Succes In CCNET");
                    }
                    break;
                }
            }

            return rs;
        }
    }
}
